/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.service.support.storage;

import org.vacoor.nothing.common.codec.Hex;
import org.vacoor.nothing.common.util.Bytes;
import org.vacoor.nothing.common.util.Randoms;

import java.util.Date;

/**
 * 按日期生成文件夹存储
 *
 * @author vacoor
 */
public abstract class DailyRollingStorageService extends DirectoryBasedStorageService {
    public static final int DEFAULT_PER_DAY_FOLDERS = 12; // 每天生成几个目录
    public static final String DATE_DIR_FMT = "%1$tY/%1$tm/%1$td/%2$04d";   // 2014/02/27/0001

    private int perDayFolders = DEFAULT_PER_DAY_FOLDERS;

    /**
     * TODO 在不同文件夹下应该不会重名吧
     *
     * @return
     */
    protected String generateFilename() {
        // return UUID.randomUUID().toString().replace("-", "");
        return Hex.encode(Bytes.toBytes(new Date().getTime() + Randoms.next(0, Long.MAX_VALUE)));
    }

    protected String getDailyRollingFolder() {
        Date date = new Date();
        int random = (int) (date.getTime() % getPerDayFolders());
        return String.format(DATE_DIR_FMT, date, random);
    }

    public int getPerDayFolders() {
        return perDayFolders;
    }

    public void setPerDayFolders(int perDayFolders) {
        this.perDayFolders = perDayFolders;
    }
}
